package com.jianying.day06;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * ClassName: Flink01_window_ProcessTime_Tumbling
 * Package: com.atguigu.day06
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/7 08:48
 * @Version: 1.0
 */
public class Flink06_WaterMark_BoundedOut {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> mapDS = env.socketTextStream("localhost", 8888).map(new WaterSensorMapFunction());
        // TODO 指定waterMark生成策略并提取事件时间字段
        SingleOutputStreamOperator<WaterSensor> waterMarkDS = mapDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        // TODO 策略：有界乱序，元素事件时间直接生成水位线 不需要考虑乱序（减去乱序时间）
                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofMillis(3))
                        // TODO 提取事件时间字段
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<WaterSensor>() {
                                    @Override
                                    public long extractTimestamp(WaterSensor waterSensor, long l) {
                                        return waterSensor.getTs();
                                    }
                                }
                        )
        );

        KeyedStream<WaterSensor, String> keyByDS = waterMarkDS.keyBy((KeySelector<WaterSensor, String>) WaterSensor::getId);

        WindowedStream<WaterSensor, String, TimeWindow> windowDS = keyByDS.window(TumblingEventTimeWindows.of(Time.milliseconds(10)));

        SingleOutputStreamOperator<String> processDS = windowDS.process(
                new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<WaterSensor, String, String, TimeWindow>.Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        long count = elements.spliterator().estimateSize();
                        String windowStart = DateFormatUtils.format(context.window().getStart(), "yyyy-MM-dd HH:mm:ss.SSS");
                        String windowEnd = DateFormatUtils.format(context.window().getEnd(), "yyyy-MM-dd HH:mm:ss.SSS");

                        out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements.toString());
                    }
                }
        );

        processDS.print();

        env.execute();

    }
}
